package com.wpre.vampiremq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:交换机
 * User: LianBao
 * Date: 2025-01-11
 * Time: 15:45
 */
public class Exchange {

    //交换机的身份标识(唯一的)
    private String name;

    //交换机类型:DIRECT,FANOUT,TOPIC
    private ExchangeType type = ExchangeType.DIRECT;//默认是直接交换机

    //交换机是否需要持久化存储,true->需要,false->不需要
    //有的交换机是需要持久化存储,有的不需要
    private boolean durable = false;

    //如果当前交换机没人使用了,就会被自动删除,false->不会自动删除
    //后续代码没有实现,RabbitMQ中实现了,(自己实现)
    private boolean autoDelete = false;

    //表示创建交换机时指定的额外参数选项,自己实现
    //为了能把arguments存储到数据库中,需要把map转换成json字符串
    private Map<String, Object> arguments = new HashMap<>();

    public ExchangeType getType() {
        return type;
    }

    public void setType(ExchangeType type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public void setArguments(String arguments) {
//        this.arguments = arguments;
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            this.arguments = objectMapper.readValue(arguments,
                    new TypeReference<HashMap<String, Object>>() {
                    });
            //第二个参数表示要转换成什么对象,如果是简单类,直接写xxx.class,如果是复杂的,就new TypeReference<xxx>() {}
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }


    //下面方法方便于测试
    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }


}
